"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');

class HTML2Markdown {
    constructor(options = {}) {
        this.options = {
            indentSize: options.indentSize || 2,
            bulletPoint: options.bulletPoint || '-'
        };
    }
    handleHeading($elem) {
        var _a;
        const tagName = ((_a = $elem.prop('tagName')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
        const level = Number(tagName.replace('h', ''));
        const text = $elem.text().trim();
        return '#'.repeat(level) + ' ' + text + '\n\n';
    }
    handleParagraph($elem) {
        return $elem.text().trim() + '\n\n';
    }
    handleList($elem, isOrdered) {
        let markdown = '';
        const items = $elem.children('li');
        const $ = cheerio.load($elem.html() || '');
        items.each((i, elem) => {
            const text = $(elem).text().trim();
            markdown += `${isOrdered ? `${i + 1}.` : this.options.bulletPoint} ${text}\n`;
        });
        return markdown + '\n';
    }
    handleLink($elem) {
        const text = $elem.text().trim();
        const href = $elem.attr('href') || '';
        return `[${text}](${href})`;
    }
    handleImage($elem) {
        const alt = $elem.attr('alt') || '';
        const src = $elem.attr('src') || '';
        return `![${alt}](${src})`;
    }
    handleElement($, elem) {
        var _a;
        const $elem = $(elem);
        const tagName = ((_a = $elem.prop('tagName')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
        switch (tagName) {
            case 'h1':
            case 'h2':
            case 'h3':
            case 'h4':
            case 'h5':
            case 'h6':
                return this.handleHeading($elem);
            case 'p':
                return this.handleParagraph($elem);
            case 'ul':
                return this.handleList($elem, false);
            case 'ol':
                return this.handleList($elem, true);
            case 'a':
                return this.handleLink($elem);
            case 'img':
                return this.handleImage($elem);
            default:
                return $elem.text().trim() + '\n';
        }
    }
    convert(html) {
        const $ = cheerio.load(html);
        let markdown = '';

        const bodyContent = $('body').length ? $('body') : $.root();
        bodyContent.children().each((_, elem) => {
            markdown += this.handleElement($, elem);
        });

        return markdown.trim();
    }
    convertFile(inputPath, outputPath) {
        try {
            console.log(`开始转换文件: ${inputPath}`);
            const html = fs.readFileSync(inputPath, 'utf-8');
            console.log(`已读取HTML文件内容，文件大小: ${html.length} 字节`);
            const markdown = this.convert(html);
            console.log(`HTML已成功转换为Markdown，准备写入文件: ${outputPath}`);
            fs.writeFileSync(outputPath, markdown);
            console.log(`✓ 转换完成: ${inputPath} -> ${outputPath}`);
        }
        catch (error) {
            console.error(`× 转换失败 ${inputPath}: ${error}`);
        }
    }
    convertDirectory(inputDir, outputDir) {
        try {
            console.log(`开始批量转换目录: ${inputDir}`);
            if (!fs.existsSync(outputDir)) {
                fs.mkdirSync(outputDir, { recursive: true });
                console.log(`创建输出目录: ${outputDir}`);
            }

            const processDirectory = (currentInputDir, currentOutputDir) => {
                const entries = fs.readdirSync(currentInputDir, { withFileTypes: true });
                const htmlFiles = entries.filter(entry => !entry.isDirectory() && entry.name.endsWith('.html'));
                const directories = entries.filter(entry => entry.isDirectory());

                console.log(`在 ${currentInputDir} 中找到 ${htmlFiles.length} 个HTML文件待转换`);

                htmlFiles.forEach((entry, index) => {
                    console.log(`\n[${index + 1}/${htmlFiles.length}] 处理文件: ${entry.name}`);
                    const inputPath = path.join(currentInputDir, entry.name);
                    const outputPath = path.join(currentOutputDir, entry.name.replace('.html', '.md'));
                    this.convertFile(inputPath, outputPath);
                });

                directories.forEach(dir => {
                    const nextInputDir = path.join(currentInputDir, dir.name);
                    const nextOutputDir = path.join(currentOutputDir, dir.name);
                    if (!fs.existsSync(nextOutputDir)) {
                        fs.mkdirSync(nextOutputDir, { recursive: true });
                        console.log(`创建输出子目录: ${nextOutputDir}`);
                    }
                    processDirectory(nextInputDir, nextOutputDir);
                });
            };

            processDirectory(inputDir, outputDir);
            console.log(`\n✓ 目录转换完成`);
            console.log(`- 输入目录: ${inputDir}`);
            console.log(`- 输出目录: ${outputDir}`);
        } catch (error) {
            console.error(`× 目录转换失败: ${error}`);
        }
    }
}
exports.default = HTML2Markdown;
// 添加命令行参数处理
if (require.main === module) {
    const args = process.argv.slice(2);
    if (args.length !== 2) {
        console.error('用法: node index.js <输入目录> <输出目录>');
        process.exit(1);
    }

    const [inputDir, outputDir] = args;
    const converter = new HTML2Markdown();
    converter.convertDirectory(inputDir, outputDir);
}
